package com.zqxq.auth.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zqxq.auth.cache.UserFuncCache;
import com.zqxq.auth.entity.bo.RoleMenuFuncBO;
import com.zqxq.auth.entity.module.Code;
import com.zqxq.auth.entity.module.Result;
import com.zqxq.auth.entity.po.UserAdmin;
import com.zqxq.auth.mapper.UserAdminMapper;
import com.zqxq.auth.service.IFuncService;
import com.zqxq.auth.service.IRoleService;
import com.zqxq.auth.service.IUserAdminService;
import com.zqxq.auth.tools.HttpKit;
import com.zqxq.auth.tools.MD5;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 管理员账号表 服务实现类
 * </p>
 *
 * @author 江枫
 * @since 2018-01-08
 */
@Service
public class UserAdminServiceImpl extends ServiceImpl<UserAdminMapper, UserAdmin> implements IUserAdminService {

    @Autowired
    private UserFuncCache userFuncCache;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IFuncService funcService;


    @Override
    public Result login(String phone, String pwd) {
        String pwdMd5 = MD5.encrypt(pwd);
//        System.out.println("密码：" + pwdMd5);
        UserAdmin userAdmin = new UserAdmin();
        userAdmin.setPhone(phone);
        userAdmin.setStop(0);//0=正常使用
        UserAdmin userAdminRet = baseMapper.selectOne(userAdmin);
        if (userAdminRet == null) {
            return new Result(Code.FAIL, "您还未注册", Code.IS_ALERT_YES);
        }
        //修改登录信息
        String login_ip = HttpKit.getClientIP();
        UserAdmin update = new UserAdmin();
        update.setUser_id(userAdminRet.getUser_id());
        update.setLogin_ip(login_ip);

        if(!pwdMd5.equals(userAdminRet.getPassword())){
            update.setLogin_fail_count(userAdminRet.getLogin_fail_count() == null ? 0 : userAdminRet.getLogin_fail_count() + 1);
            baseMapper.updateById(update);
            return new Result(Code.FAIL, "手机号或密码错误", Code.IS_ALERT_YES);
        }
        update.setLast_login_time(new Date());
        baseMapper.updateById(update);

        userAdminRet.setLogin_ip(login_ip);
        String token_id = userFuncCache.createTokenId(userAdminRet.getUser_id(), userAdminRet);//生成token_id,并加入缓存
        List<RoleMenuFuncBO> userMenuList = funcService.getUserRoleFunc(userAdminRet.getRole_id());
        Map data = new HashMap();
        data.put("token_id", token_id);
        data.put("userMenuList", userMenuList);
        data.put("userInfo", userAdminRet);
        return new Result(data);
    }

    @Override
    public Result loginOut(String token_id) {
        if (token_id == null) {
            return new Result();
        }
        userFuncCache.deleteToken(token_id);
        return new Result();
    }

    @Override
    public Result updatePwd(String token_id, String old_pwd, String new_pwd) {
        if (token_id == null || old_pwd == null || new_pwd == null) {
            return new Result(Code.FAIL, "非法参数");
        }
        Map data = new HashMap();
        if (old_pwd.equals(new_pwd)) {
            data.put("token_id", token_id);
            return new Result(data);
        }

        UserAdmin userAdmin = userFuncCache.getUserAdmin(token_id);
        String old_pwd_md5 = MD5.encrypt(old_pwd);
        if (!old_pwd_md5.equals(userAdmin.getPassword())) {
            return new Result(Code.FAIL, "用户原始密码错误");
        }

        String new_pwd_md5 = MD5.encrypt(new_pwd);
        UserAdmin update = new UserAdmin();
        update.setUser_id(userAdmin.getUser_id());
        update.setPassword(new_pwd_md5);
        baseMapper.updateById(update);

        userAdmin.setPassword(new_pwd_md5);
        data.put("token_id", userFuncCache.createTokenId(userAdmin.getUser_id(), userAdmin));
        return new Result(data);
    }

    @Override
    public Result getUserList(Long role_id, Integer currentPage, Integer pageSize) {
        if (currentPage == null || currentPage < 1) {
            currentPage = 1;
        }
        if (pageSize == null || pageSize < 0) {
            pageSize = 10;
        }
        long offset = (currentPage - 1) * pageSize;

        String roles = roleService.getChildrenRoleString(role_id.toString());
        List<Map> userList = baseMapper.getUserList(roles, offset, pageSize);
        Long total = baseMapper.getUserTotal(roles);
        Map data = new HashMap();
        data.put("records", userList);
        data.put("total", total);
        return new Result(data);
    }

    @Override
    public Result saveUser(UserAdmin userAdmin, UserAdmin operateUser) {
        String phone = userAdmin.getPhone();
        String pwd = userAdmin.getPassword();
        if (userAdmin.getUser_id() == null) {
            if (StringUtils.isEmpty(phone)) {
                return new Result(Code.FAIL, "登录账号不能为空");
            }
            if (StringUtils.isEmpty(userAdmin.getUser_name())) {
                return new Result(Code.FAIL, "成员名称不能为空");
            }
            if (StringUtils.isEmpty(pwd)) {
                return new Result(Code.FAIL, "用户登录密码不能为空");
            }
        }
        if (!StringUtils.isEmpty(phone)) {
            //验证登录账号不能重复
            if (!validPhone(phone, userAdmin.getUser_id())) {
                return new Result(Code.FAIL, "登录账号重复");
            }
        }

        boolean isUpdatePwd = false;
        if (userAdmin.getUser_id() == null) {
            userAdmin.setAdduser(operateUser.getUser_id());
            userAdmin.setReg_time(new Date());
            isUpdatePwd = true;
        } else if (!StringUtils.isEmpty(pwd)) {
            UserAdmin ua = baseMapper.selectById(userAdmin.getUser_id());
            if (!ua.getPassword().equals(pwd)) {
                isUpdatePwd = true;
            }
        }
        if (isUpdatePwd) {
            userAdmin.setPassword(MD5.encrypt(pwd));
        }

        this.insertOrUpdate(userAdmin);
        return new Result();
    }

    @Override
    public Result isPhonePass(String phone, Long user_id) {
        if (StringUtils.isEmpty(phone)) {
            return new Result(Code.FAIL, "登录账号不能为空");
        }
        return new Result(this.validPhone(phone, user_id));
    }

    @Override
    public Result getUserInfoByUserId(Long user_id) {
        if (user_id == null) {
            return new Result(Code.FAIL, "用户id 不能为空");
        }
        return new Result(baseMapper.selectById(user_id));
    }

    /**
     * 判断手机号(账号)是否合法（不重复）
     * @param phone
     * @param user_id
     * @return true = 合法
     */
    private boolean validPhone(String phone, Long user_id) {
        UserAdmin userAdmin = new UserAdmin();
        userAdmin.setPhone(phone);
        Wrapper wrapper = new EntityWrapper(userAdmin);
        List<UserAdmin> list = baseMapper.selectList(wrapper);
        if (list == null ||list.isEmpty()) {
            return true;
        }
        if (list.size() < 2) {
            if (user_id == list.get(0).getUser_id()) {
                return true;
            }
        }
        return false;
    }
    public static void main(String[] args) {
        String pwdMd5 = MD5.encrypt("hz1866");
        System.out.println(pwdMd5);
    }
}
